package mobi.weq.servlets;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import javax.xml.ws.http.HTTPException;

import mobi.weq.dao.ObservationDao;
import mobi.weq.model.Observation;
import mobi.weq.util.Generator;

import org.apache.commons.io.FilenameUtils;

import com.google.gson.Gson;

@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB
maxFileSize = 1024 * 1024 * 10, maxRequestSize = 1024 * 1024 * 50)
public class ObservationServlet extends HttpServlet {

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, HTTPException, ServletException {
		String current = req.getParameter("current");
		String daysString = req.getParameter("days");
		if (current != null) {
			Observation observation = Generator
					.generateEdinburghCurrentObservation();
			Gson gson = new Gson();
			String json = gson.toJson(observation);
			resp.getWriter().print(json);

		} else if (daysString != null) {
			int days = Integer.valueOf(daysString);
			ArrayList<Observation> observations = Generator
					.generateEdinburghObservations(days);
			Gson gson = new Gson();
			String json = gson.toJson(observations);
			resp.getWriter().print(json);
		} else {
			req.getRequestDispatcher("/jsp/observation.jsp").forward(req, resp);
		}
	}

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws HTTPException, IOException, ServletException {
		System.out.println("ObservationServlet.doPost()");
		Observation ob = new Observation();

		/* for uploaded image */
		String rootPath = req.getServletContext().getRealPath("");
		String imagePath = File.separator + "user-images";
		Part filePart = req.getPart("image");

		/*---------------------*/
		String no2String = req.getParameter("no2");
		double no2;
		try {
			no2 = Double.parseDouble(no2String);
		} catch (Exception e) {
			no2 = 0.0;
		}

		String coString = req.getParameter("co");
		double co;
		try {
			co = Double.parseDouble(coString);
		} catch (Exception e) {
			co = 0.0;
		}

		String so2String = req.getParameter("so2");
		double so2;
		try {
			so2 = Double.parseDouble(so2String);
		} catch (Exception e) {
			so2 = 0.0;
		}

		String o3String = req.getParameter("o3");
		double o3;
		try {
			o3 = Double.parseDouble(o3String);
		} catch (Exception e) {
			o3 = 0.0;
		}

		String pm10String = req.getParameter("pm10");
		double pm10;
		try {
			pm10 = Double.parseDouble(pm10String);
		} catch (Exception e) {
			pm10 = 0.0;
		}

		String pm2p5String = req.getParameter("pm2p5");
		double pm2p5;
		try {
			pm2p5 = Double.parseDouble(pm2p5String);
		} catch (Exception e) {
			pm2p5 = 0.0;
		}

		String user_categorization = req.getParameter("user_categorization");
		System.out.println(req.getParameterMap());

		String user_comments = req.getParameter("user_comments");

		String filename = getFilename(filePart);
		String extension = FilenameUtils.getExtension(filename);
		imagePath += File.separator + ob.getId() + "." + extension;

		System.out.println(getServletContext().getRealPath("."));
		String image_path = imagePath;

		String image_name = filename;

		String image_description = req.getParameter("image_description");

		String latitudeString = req.getParameter("latitude");
		double latitude;
		try {
			latitude = Double.parseDouble(latitudeString);
		} catch (Exception e) {
			latitude = 0.0;
		}

		String longitudeString = req.getParameter("longitude");
		double longitude;
		try {
			longitude = Double.parseDouble(longitudeString);
		} catch (Exception e) {
			longitude = 0.0;
		}

		String altitudeString = req.getParameter("altitude");
		double altitude;
		try {
			altitude = Double.parseDouble(altitudeString);
		} catch (Exception e) {
			altitude = 0.0;
		}

		ob.setNo2(no2);
		ob.setCo(co);
		ob.setSo2(so2);
		ob.setO3(o3);
		ob.setPm10(pm10);
		ob.setPm2p5(pm2p5);
		ob.setAltitude(altitude);
		ob.setLatitude(latitude);
		ob.setLongitude(longitude);
		if (image_name.trim().length() > 1) {
			ob.setImage_name(image_name);
			ob.setImage_path(image_path);
			ob.setImage_description(image_description);
		}

		ob.setUser_categorization(user_categorization);
		ob.setUser_comments(user_comments);

		ObservationDao obd = new ObservationDao();

		try {
			obd.addObservations(ob);
			if (filename.length() != 0) {
				filePart.write(rootPath + imagePath);
				System.out.println(imagePath);
			}

		} catch (SQLException e) {
			e.printStackTrace();
		}
		req.getRequestDispatcher("observation.jsp").forward(req, resp);

	}

	private String getFilename(Part part) {
		for (String cd : part.getHeader("content-disposition").split(";")) {
			if (cd.trim().startsWith("filename")) {
				String filename = cd.substring(cd.indexOf('=') + 1).trim()
						.replace("\"", "");
				return filename.substring(filename.lastIndexOf('/') + 1)
						.substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
			}
		}
		return null;
	}
}
